<?php
namespace Seller\Controller;
use Think\AjaxPage;
use Think\Controller;

class MembersController extends CommonController
{
    public function _initialize()
    {
        // 数组存放不需添加进权限控制的方法
        // 注意：请把所有大写字母改成小写
        $params = array(
            'downloadtemplate' ,'searchagent',"assign_member","doassign","add_member","ajax_member_list",
            "ajax_normal_list","addmemeber","ajax_change_list","ajax_account_list",
            "member_edit","member_view","to_agent","member_add"
        );
        parent::_initialize($params);
    }

    // 代理分配的客户资源
    public function members()
    {
        $this->display();
    }

    // 客户分配
    public function assign_member()
    {
        $where['agent_id'] = array("eq" ,0);
        if(isset($_REQUEST['cName']))
        {
            $cName = trim($_REQUEST['cName']);
            if($cName != ''){
                $cWhere['member_name'] = array("like" ,"%$cName%");
                $cWhere['mobile'] = array("eq" ,$cName);
                $cWhere['wx'] = array("like" ,"%$cName%");
                $cWhere['_logic'] = 'or';
                $where['_complex'] = $cWhere;
            }
        }
        $count = M('agent_members')->where($where)->count();
        $page = set_page($count, C('PAGE_NUM'));
        $members = M('agent_members')->where($where)->limit($page->firstRow.','.$page->listRows)
            ->order('member_id DESC')->select();

        $show = $page->show();
        $this->assign('page',$show);
        $this->assign('members', $members);
        $this->display();
    }

    // 分配
    public function doAssign()
    {
        if(IS_POST){
            $agent_id = intval(I("post.agent_id"));
            $member_ids = I("post.member_id");
            if(!is_array($member_ids) || empty($member_ids)){
                $this->error("未选择需分配客户" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            foreach($member_ids as $member_id){
                $is_doassign = M("agent_members")->where(array("member_id"=>$member_id))->find();
                if(!empty($is_doassign["agent_id"])){
                    $this->error($is_doassign['member_name']."已经被分配了",$_SERVER['HTTP_REFERER'],1);
                }
                if(!_int($member_id)){
                    $this->error("客户ID有误" ,$_SERVER['HTTP_REFERER'] ,1);
                }
            }
            $agent_name = M("agent")->where("agent_id = $agent_id")->getField("agent_name");
            M("agent_members")->where("agent_id = 0 AND member_id IN (".implode("," ,$member_ids).")")->save(array(
                "agent_id" => $agent_id,
                "agent_name" => $agent_name
            ));
            $this->success("分配成功" ,$_SERVER['HTTP_REFERER'] ,1);
        }else{
            exit("error");
        }
    }

    // 添加客户资源
    public function add_member()
    {
        if(IS_POST)
        {
            $member_name = trim(I("post.member_name"));
            $mobile = trim(I("post.mobile"));
            $wx = trim(I("post.wx"));
            $address = trim(I("post.address"));
            $agent_id = intval(I("post.agent_id"));
            if(!empty($mobile)){
                if(!is_mobile($mobile)){
                    $this->error("手机号码格式有误" ,$_SERVER['HTTP_REFERER'] ,1);
                }
            }
            $agent_name = '#';
            if($agent_id != 0){
                $agent_name = M("agent")->where("agent_id = $agent_id")->getField("agent_name");
            }
            $res = M("agent_member")->where(array("mobile"=>$mobile,'shop_id'=>session("shop_id")))->find();
            $rep = M("agent_member")->where(array("wx"=>$wx,'shop_id'=>session("shop_id")))->find();
            if(!empty($res)||!empty($rep)){
                $this->error("已存在此手机号或微信号的客户",$_SERVER['HTTP_REFERER'] ,1);
            }
            $rs = M("agent_members")->add(array(
                'agent_name' => $agent_name,
                'agent_id' => $agent_id,
                'member_name' => $member_name,
                'mobile' => $mobile,
                'wx' => $wx,
                'address' => $address,
                'send_time' => date("Y-m-d H:i:s", time()),
                'shop_id' =>session("shop_id")
            ));
            if($rs !== false){
                $this->success("添加成功" ,U('Members/members') ,1);
            }else{
                $this->error("添加失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $this->display();
        }
    }

    // 模糊搜索代理
    public function searchAgent()
    {
        $agentName = trim(I('post.aName'));
        $shop_id = session("shop_id");
        if($agentName != ''){
            $agentList = M("agent")->where("is_agent = 1 AND agent_name LIKE '%$agentName%' AND u_status = 1 AND shop_id = $shop_id")->select();
            if($agentList) {
                $this->ajaxReturn($agentList);
            }
        }
    }

    // 模板下载
    public function downloadTemplate()
    {
        ob_start();
        $name = "客户导入专用模板.xls";
        header( "Content-type:  application/octet-stream ");
        header( "Accept-Ranges:  bytes ");
        header( "Content-Disposition:  attachment;  filename= {$name}");
        $size = readfile("./Data/member/importTemplate.xls");
        header( "Accept-Length: " .$size);
    }

    // ajax 读取客户列表
    public function ajax_member_list()
    {
        $where = '1 = 1 '; // 搜索条件
        $aName = I('aName') ? trim(I('aName')) : '';
        if($aName) $where = "$where AND (member_name like '%$aName%' OR mobile like '%$aName%' OR wx like '%$aName%' OR agent_name like '%$aName%')" ;

        $count = M('agent_members')->where($where)->where(array("shop_id"=>session("shop_id")))->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $members = M('agent_members')->where($where)->where(array("shop_id"=>session('shop_id')))->limit($Page->firstRow.','.$Page->listRows)->order($order_str)->select();
        $this->assign('page',$show);
        $this->assign('members', $members);
        $this->display();
    }

    // 普通用户列表
    public function member_list()
    {
        $this->display();
    }

    // 普通用户列表
    public function member_amt()
    {
        $this->display();
    }

    // ajax 读取普通会员列表
    public function ajax_normal_list()
    {
        $where = 'is_agent = 2 '; // 搜索条件
        $shop_id = session("shop_id");
        $where = "$where AND shop_id = $shop_id";
        (I('u_status') !== '') && $where = "$where AND u_status = ".I('u_status') ;
        // 关键词搜索
        $mName = I('mName') ? trim(I('mName')) : '';
        if($mName) $where = "$where AND (agent_name like '%$mName%' or mobile like '%$mName%')" ;
        $count = D('AgentView')->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $agentList = D('AgentView')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('agents',$agentList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    // 添加普通会员
    public function addmember()
    {
        if(IS_POST)
        {
            $mobile = to_int(I("post.mobile"));
            $c_name = trim(I("post.mem_name"));
            $email = trim(I("post.email"));
            $pwd = trim(I("post.pwd"));
            $shop_id = session('shop_id');
            if(!is_mobile($mobile)){
                $this->error("手机号码格式有误" ,U('Members/member_add') ,1);
            }
            // 通过用户名/手机查询是否已添加过改用户
            $agent = M("agent")->where("mobile  = '$mobile' and shop_id = %d" ,array($shop_id))->find();
            if($agent){
                $this->error("已存在此会员，请仔细核对" ,U('Members/member_add') ,1);
            }
            // 查询是否开启注册审核
            $is_audit = M("config")->where("conf_key => 'agent_check'")->getField("conf_value");
            if($is_audit == 1){
                $audit_c = 2;
            }else{
                $audit_c = 1;
            }
            $rs = M("agent")->add(array(
                'agent_name' => $c_name,
                'parent_id' => 0,
                'u_status' => $audit_c,
                'mobile' => $mobile,
                'shop_id' => $shop_id
            ));
            if($rs !== false){
                $id = M("agent")->getLastInsId();
                $salt = substr(md5(time(). $id) ,-8);
                M("agent_info")->add(array(
                    "agent_id" => $id,
                    "password" => md5(md5($pwd) .$salt),
                    "salt" => $salt,
                    "email" => $email,
                    "reg_time" => date("Y-m-d H:i:s" ,time()),
                    "reg_ip" => get_client_ip()
                ));
                $this->success("添加成功" ,U('Members/member_list'),1);
            }else{
                $this->error("添加失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            exit("error");
        }
    }

    // ajax 读取资金变动列表
    public function ajax_change_list()
    {
        $shop_id = session('shop_id');
        $where = "agent.shop_id = {$shop_id} and agent.is_agent = 2 "; // 搜索条件
        (I('status') !== '') && $where = "$where AND amt_type = ".I('status') ;
        // 关键词搜索
        $user = I('user') ? trim(I('user')) : '';
        $user_ids = array();
        if($user) {
            $us = M("agent")->where("agent_name LIKE '%$user%' AND shop_id = $shop_id AND is_agent = 2")->select();
            if($us){
                foreach($us as $u){
                    $user_ids[] = $u["agent_id"];
                }
                $where = "$where AND amt_change.agent_id IN (".implode("," ,$user_ids).")" ;
            }
        }
        $count = D("AmtAgentView")->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $amt_changes = D("AmtAgentView")->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign("amt_changes" ,$amt_changes);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    // 普通用户充值记录列表
    public function members_act()
    {
        $this->display();
    }

    // ajax 会员读取列表
    public function ajax_account_list()
    {
        $account_d = D("AccountView");
        $where = "agent.is_agent = 2 ";
        // 关键词搜索
        $aName = I('aName') ? trim(I('aName')) : '';
        if($aName) $where = "$where AND (agent.agent_name like '%$aName%')" ;
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $count = $account_d->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $accountlist = $account_d->where($where)->limit($Page->firstRow.','.$Page->listRows)->order($order_str)->select();
        $show = $Page->show();
        $payment = array();
        $payments = M("payment")->field("p_id,p_name")->select();
        foreach($payments as $pay){
            $payment[$pay['p_id']] = $pay['p_name'];
        }
        $this->assign('payment' ,$payment);
        $this->assign('page',$show);
        $this->assign('accountlist',$accountlist);
        $this->display();
    }

    // 会员编辑
    public function member_edit()
    {
        if(IS_POST)
        {
            $agent_id = to_int(I("post.agent_id"));
            $npwd = trim(I("post.npwd"));
            $mem_name = trim(I("post.mem_name"));
            $email = trim(I("post.email"));
            // 修改密码
            if($npwd != ""){
                $salt = M("agent_info")->where("agent_id = %d" ,array($agent_id))->getField("salt");
                $save_data["password"] = md5(md5($npwd) .$salt);
            }
            $save_data["email"] = $email;
            M("agent_info")->where("agent_id = %d" ,array($agent_id))->save($save_data);
            M("agent")->where("agent_id = %d" ,array($agent_id))->setField("agent_name" ,$mem_name);
            $this->success("修改成功" ,U('Members/member_list') ,1);
        }else{
            $agent_id = to_int(I('get.id'));
            $where['shop_id'] = session("shop_id");
            $agent = D("AgentView")->where("agent.agent_id = %d" ,array($agent_id))->find();
            if(!$agent){
                $this->error("参数错误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $this->assign("agent" ,$agent);
            $this->display();
        }
    }

    // 客户详情
    public function member_view()
    {
        $agent_id = to_int(I('get.id'));
        $agent = D("AgentView")->where("agent.agent_id = $agent_id")->find();
        if(!$agent){
            $this->success("请求失败" ,$_SERVER['HTTP_REFERER'] ,1);
        }
        $agentAddress = M('agent_address')->where( array('agent_id' => $agent_id) )->select();
        $this->assign('agentAddress', $agentAddress);
        $this->agent = $agent;
        $this->display();
    }

    // 普通用户转化代理
    public function to_agent()
    {
        if(IS_POST)
        {
            //上级代理ID
            $to_id = to_int(I("post.to_id"));
            //自己的ID
            $agent_id = to_int(I("post.agent_id"));
            $agent = M("agent")->where("agent_id = %d", array($agent_id))->find();
            $rs = M("agent")->where("agent_id = %d", array($agent_id))->save(array(
                'parent_id' => $to_id,
                'is_agent' => 1
            ));
            if($rs !== false){
//                $npassword = md5(md5($npwd) .$agent['salt']);
//                M("agent_info")->where("agent_id = %d", array($agent_id))->setField("password" ,$npassword);
                $this->redirect(U('Agent/edit_agent' ,array("id" => $agent_id)));
            }else{
                $this->error("修改失败" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        }else{
            $agent_id = I("get.id");
            $agent = D("AgentView")->where("agent.agent_id = %d",array($agent_id))->find();
            if(!$agent){
                $this->error("无此用户信息" ,$_SERVER['HTTP_REFERER'] ,1);
            }
            $this->assign("agent_id",$agent_id);
            $this->assign('agent' ,$agent);
            $this->display();
        }
    }

    public function member_add(){
        $this->display();
    }
}